package com.itheima04;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Demo4 implements Runnable {
    private int tickets = 100; //共享数据

    Lock l = new ReentrantLock();

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(100);

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //上锁
            l.lock(); {
                if (tickets <= 0) {
                    break;
                }
            }
            try {
                Thread.sleep(100);
                String name = Thread.currentThread().getName();
                System.out.println(name + "正在卖第" + (100 - tickets + 1) + "张票 ,还剩" + --tickets + "张票");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                l.unlock(); //当前线程解锁后，其他线程才可以执行同步内容
            }
        }

    }
}
